<template>
  <el-dialog v-model="dialogVisible" title="入库" width="600px" :before-close="handleClose">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <!-- 商品名称 -->
      <el-form-item label="商品名称" prop="product_name">
        <el-select
          v-model="form.product_name"
          placeholder="请选择商品"
          style="width: 100%"
          clearable
          @change="handleProductChange"
        >
          <el-option
            v-for="item in productList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 数量 -->
      <el-form-item label="数量" prop="quantity">
        <el-input v-model="form.quantity" disabled style="width: 100%" />
      </el-form-item>

      <!-- 原仓库 -->
      <el-form-item label="原仓库" prop="original_warehouse">
        <el-input v-model="form.original_warehouse" disabled style="width: 100%" />
      </el-form-item>

      <!-- 入库类型 -->
      <el-form-item label="入库类型" prop="warehouse_type">
        <el-select
          v-model="form.warehouse_type"
          placeholder="请选择入库类型"
          style="width: 100%"
          clearable
          @change="handleWarehouseTypeChange"
        >
          <el-option
            v-for="item in warehouseTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 备注 -->
      <el-form-item v-if="showRemark" label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注"
          style="width: 100%"
        />
      </el-form-item>

      <!-- 仓库选择 -->
      <el-form-item label="仓库选择" prop="target_warehouse">
        <el-tree-select
          v-model="form.target_warehouse"
          :data="warehouseList"
          placeholder="请选择仓库"
          style="width: 100%"
          clearable
          filterable
          :props="{
            value: 'value',
            label: 'label',
            children: 'children',
            disabled: 'disabled'
          }"
          check-strictly
          :render-after-expand="false"
        />
      </el-form-item>

      <!-- 入库数量 -->
      <el-form-item label="入库数量" prop="inbound_quantity">
        <div style="display: flex; align-items: center; gap: 10px">
          <el-input-number
            v-model="form.inbound_quantity"
            :min="0"
            :max="form.quantity"
            :disabled="!form.quantity"
            placeholder="请输入入库数量"
            style="flex: 1"
            controls-position="right"
            @change="handleInboundQuantityChange"
          />
          <el-button
            type="primary"
            @click="handleAddToQueue"
            :disabled="!form.inbound_quantity || form.inbound_quantity <= 0"
          >
            加入队列
          </el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- 队列显示区域 -->
    <div class="queue-section">
      <h4>入库队列</h4>
      <div class="queue-list">
        <div v-for="(item, index) in queueList" :key="index" class="queue-item">
          <div class="item-info">
            <span class="product-name">{{ item.product_name_label }}</span>
            <span class="quantity-info">数量: {{ item.inbound_quantity }}</span>
            <span class="warehouse-info">仓库: {{ getWarehouseName(item.target_warehouse) }}</span>
          </div>
          <div class="item-status">准备入库</div>
          <el-button size="small" type="danger" @click="removeFromQueue(index)"> 删除 </el-button>
        </div>
        <div v-if="queueList.length === 0" class="empty-queue"> 暂无商品在队列中 </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认入库</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
// 向父组件派发事件
const emit = defineEmits<{ (e: 'refresh'): void }>()
import {
  getReturnOrderDetailApi,
  getWarehouseResourceApi,
  getEnumApi,
  submitStockApi
} from '@/api/orderReturn'

const dialogVisible = ref(false)
const formRef = ref()

// 队列数据
const queueList = ref<any[]>([])

// 是否显示备注
const showRemark = ref(false)

// 退货单ID
const returnOrderId = ref<number>()

// 表单数据
const form = reactive({
  product_name: undefined as number | undefined,
  quantity: 0,
  original_warehouse: '',
  warehouse_type: '',
  remark: '',
  target_warehouse: undefined as number | undefined,
  inbound_quantity: 0
})

// 表单验证规则
const rules = {
  product_name: [{ required: true, message: '请选择商品名称', trigger: 'change' }],
  warehouse_type: [{ required: true, message: '请选择入库类型', trigger: 'change' }],
  target_warehouse: [{ required: true, message: '请选择仓库', trigger: 'change' }],
  inbound_quantity: [
    { required: true, message: '请输入入库数量', trigger: 'blur' },
    { type: 'number' as const, min: 0, message: '入库数量不能小于0', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!form.quantity) {
          callback(new Error('请先选择商品'))
        } else if (value && value > form.quantity) {
          callback(new Error(`入库数量不能大于${form.quantity}`))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 商品列表数据
const productList = ref<
  Array<{
    label: string
    value: number
    pending_qty?: number
    warehouses_name?: string
  }>
>([])

const warehouseTypeList = ref<any[]>([])

const warehouseList = ref<any[]>([])

// 打开弹窗
const open = async (row?: any) => {
  dialogVisible.value = true

  try {
    // 获取仓库数据
    const warehouseResp = await getWarehouseResourceApi()
    const warehouseData = warehouseResp.data?.warehouse_parent_tree || []

    // 为一级菜单添加disabled属性
    warehouseList.value = warehouseData.map((group: any) => ({
      ...group,
      disabled: true, // 一级菜单禁用
      children: group.children?.map((child: any) => ({
        ...child,
        disabled: false // 二级菜单可用
      }))
    }))

    // 获取枚举数据
    const enumResp = await getEnumApi({ field: 'all' })
    warehouseTypeList.value = enumResp.data.stock_type || []

    if (row?.id) {
      // 保存退货单ID
      returnOrderId.value = row.id

      // 获取退货单详情
      const resp = await getReturnOrderDetailApi(row.id)
      const detailData = resp.data

      // 更新商品列表为products_list数据
      if (detailData.products_list && detailData.products_list.length > 0) {
        productList.value = detailData.products_list.map((item: any) => ({
          label: item.product_name,
          value: item.product_id,
          pending_qty: item.pending_qty,
          warehouses_name: item.warehouses_name
        }))
      }

      // 重置表单
      form.product_name = undefined
      form.quantity = 0
      form.original_warehouse = ''
      form.warehouse_type = ''
      form.remark = ''
      form.target_warehouse = undefined
      form.inbound_quantity = 0

      // 重置备注显示状态
      showRemark.value = false

      // 清空队列
      queueList.value = []
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  }
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  // 重置表单
  formRef.value?.resetFields()
  // 重置退货单ID
  returnOrderId.value = undefined
}

// 加入队列
const handleAddToQueue = () => {
  // 验证必填字段
  if (
    !form.product_name ||
    !form.warehouse_type ||
    !form.target_warehouse ||
    !form.inbound_quantity
  ) {
    ElMessage.warning('请填写完整的入库信息')
    return
  }

  // 验证入库数量不能大于可用数量
  if (form.inbound_quantity > form.quantity) {
    ElMessage.error(`入库数量不能大于可用数量：${form.quantity}`)
    return
  }

  // 验证入库数量必须大于0
  if (form.inbound_quantity <= 0) {
    ElMessage.error('入库数量必须大于0')
    return
  }

  // 获取选中商品的名称
  const selectedProduct = productList.value.find((item) => item.value === form.product_name)
  const productName = selectedProduct?.label || ''

  // 检查是否已存在相同商品
  const existingIndex = queueList.value.findIndex(
    (item) =>
      item.product_name === form.product_name && item.target_warehouse === form.target_warehouse
  )

  if (existingIndex !== -1) {
    ElMessage.warning('该商品已存在于队列中')
    return
  }

  // 添加到队列
  queueList.value.push({
    ...form,
    product_name_label: productName, // 添加商品名称标签用于显示
    id: Date.now() // 临时ID
  })
}

// 从队列中删除
const removeFromQueue = (index: number) => {
  queueList.value.splice(index, 1)
}

// 商品选择变化处理
const handleProductChange = (productId: number) => {
  const selectedProduct = productList.value.find((item) => item.value === productId)
  if (selectedProduct) {
    form.quantity = selectedProduct.pending_qty || 0
    form.original_warehouse = selectedProduct.warehouses_name || ''
    // 重置入库数量为0
    form.inbound_quantity = 0
  }
}

// 入库类型变化处理
const handleWarehouseTypeChange = (value: number) => {
  // 当选择报损入库（value为2）时显示备注
  showRemark.value = value === 2
  // 如果不是报损入库，清空备注
  if (value !== 2) {
    form.remark = ''
  }
}

// 入库数量变化处理
const handleInboundQuantityChange = (value: number) => {
  // 如果没有选择商品，不允许输入
  if (!form.quantity) {
    form.inbound_quantity = 0
    return
  }

  // 如果入库数量大于可用数量，自动调整为可用数量
  if (value && value > form.quantity) {
    form.inbound_quantity = form.quantity
    ElMessage.warning(`入库数量已调整为最大可用数量：${form.quantity}`)
  }
}

// 获取仓库名称
const getWarehouseName = (value: number) => {
  // 递归查找仓库名称
  const findWarehouseName = (nodes: any[]): string | null => {
    for (const node of nodes) {
      if (node.value === value) {
        return node.label
      }
      if (node.children) {
        const result = findWarehouseName(node.children)
        if (result) return result
      }
    }
    return null
  }

  const name = findWarehouseName(warehouseList.value)
  return name || value.toString()
}

// 确认入库
const handleConfirm = async () => {
  if (queueList.value.length === 0) {
    ElMessage.warning('请先添加商品到队列')
    return
  }

  if (!returnOrderId.value) {
    ElMessage.error('退货单ID不存在')
    return
  }

  try {
    // 构建提交数据
    const stockList = queueList.value.map((item: any) => ({
      product_id: item.product_name,
      number: item.inbound_quantity,
      type: item.warehouse_type,
      wid: item.target_warehouse,
      remark: item.remark || null
    }))

    const submitData = {
      id: returnOrderId.value,
      stock_list: stockList
    }

    // 提交入库
    const response = await submitStockApi(submitData)

    // 检查返回的code
    if (response.code === 0) {
      ElMessage.success('入库成功')
      emit('refresh')
      handleClose()
    } else {
      // 显示服务器返回的错误信息
      const errorMessage = (response as any).message || '入库失败'
      ElMessage.error(errorMessage)
    }
  } catch (error) {
    console.error('入库失败:', error)
    ElMessage.error('入库失败')
  }
}

// 暴露方法给父组件
defineExpose({
  open
})
</script>

<style lang="less" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.queue-section {
  padding-top: 20px;
  margin-top: 20px;
  border-top: 1px solid #eee;

  h4 {
    margin: 0 0 15px;
    color: #333;
  }

  .queue-list {
    max-height: 200px;
    padding: 10px;
    overflow-y: auto;
    border: 1px solid #eee;
    border-radius: 4px;
  }

  .queue-item {
    display: flex;
    padding: 10px;
    margin-bottom: 8px;
    border-bottom: 1px solid #f0f0f0;
    justify-content: space-between;
    align-items: center;

    &:last-child {
      margin-bottom: 0;
      border-bottom: none;
    }

    .item-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 4px;

      .product-name {
        font-weight: bold;
        color: #333;
      }

      .quantity-info,
      .warehouse-info {
        font-size: 12px;
        color: #666;
      }
    }

    .item-status {
      margin: 0 10px;
      font-size: 12px;
      color: #67c23a;
    }
  }

  .empty-queue {
    padding: 20px;
    color: #999;
    text-align: center;
  }
}
</style>
